package com.uzai.console.service.mini.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.dto.base.UzaiRespVo;
import com.uzai.common.enums.mini.MiniOrderServiceStatus;
import com.uzai.common.enums.mini.MiniOrderServiceType;
import com.uzai.common.enums.mini.MiniOrderStatus;
import com.uzai.common.enums.mini.MiniTradeStatus;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.cashier.CashierWxPayClient;
import com.uzai.console.cashier.dto.WxOrderQueryDto;
import com.uzai.console.cashier.enums.TradeStatusEnum;
import com.uzai.console.cashier.param.CashierWechatPayParam;
import com.uzai.console.cashier.param.CashierWechatPayQueryParam;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.dto.mini.miniorderservice.*;
import com.uzai.console.entity.*;
import com.uzai.console.mapper.*;
import com.uzai.console.service.mini.MiniOrderServiceService;
import com.uzai.console.vo.mini.miniorder.MiniOrderVo;
import com.uzai.console.vo.mini.miniorderservice.MiniOrderServiceVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author liuqi
 * @date 2021年08月23日 20:25
 */
@Service
public class MiniOrderServiceServiceImpl implements MiniOrderServiceService {

    Logger logger = LoggerFactory.getLogger(MiniOrderServiceServiceImpl.class);

    @Autowired
    private MiniOrderServiceMapper miniOrderServiceMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private MiniOrderMapper miniOrderMapper;
    @Autowired
    private MiniUserMapper miniUserMapper;
    @Autowired
    private UserTypeMapper userTypeMapper;
    @Autowired
    private CashierWxPayClient cashierWxPayClient;
    @Autowired
    private DeviceMiniInfoMapper deviceMiniInfoMapper;
    @Autowired
    private MiniTradeMapper miniTradeMapper;


    /**
     * 分页查询小程序团购售后列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @return MiniOrderServiceVo
     */
    public Page<MiniOrderServiceVo> findMiniOrderServiceByPage(MiniOrderServiceQuery miniOrderServiceQuery){
        //新建返回到页面的LIST对象
        List<MiniOrderServiceVo> miniOrderServiceVoList = new ArrayList<>();
        //返回到页面分页对象
        Page<MiniOrderServiceVo> pageVo = new Page<>();

        //执行分页查询对象
        Page<MiniOrderService> page = new Page<>();
        miniOrderServiceQuery.convert(page);
        List<MiniOrderService> miniOrderServiceList = miniOrderServiceMapper.findByList(page, miniOrderServiceQuery);

        if(miniOrderServiceList != null && miniOrderServiceList.size() > 0){
            for (MiniOrderService miniOrderService : miniOrderServiceList){
                MiniOrderServiceVo miniOrderServiceVo = new MiniOrderServiceVo();
                BeanUtils.copyProperties(miniOrderService, miniOrderServiceVo);

                if(miniOrderService.getStatus() != null){
                    MiniOrderServiceStatus miniOrderServiceStatus = MiniOrderServiceStatus.getByCode(miniOrderService.getStatus());
                    if(miniOrderServiceStatus != null){
                        miniOrderServiceVo.setStatusName(miniOrderServiceStatus.getDesc());
                    }
                }

                //订单详情
                if(miniOrderService.getOrderId() != null){
                    MiniOrder miniOrder = miniOrderMapper.selectById(miniOrderService.getOrderId(), miniOrderService.getMerId());
                    if(miniOrder != null){
                        MiniOrderVo miniOrderVo = new MiniOrderVo();
                        BeanUtils.copyProperties(miniOrder, miniOrderVo);
                        miniOrderServiceVo.setMiniOrderVo(miniOrderVo);
                    }
                }

                //会员类型
                if(miniOrderService.getUserId() != null){
                    MiniUser miniUser = miniUserMapper.selectById(miniOrderService.getUserId(), miniOrderService.getMerId());
                    if(miniUser != null){
                        miniOrderServiceVo.setNickName(miniUser.getNickName());
                        miniOrderServiceVo.setUserRemark(miniUser.getRemark());
                        if(miniUser.getUserType() != null){
                            UserType userType = userTypeMapper.selectById(miniUser.getUserType(), miniUser.getMerId());
                            if(userType != null){
                                miniOrderServiceVo.setUserType(miniUser.getUserType());
                                miniOrderServiceVo.setUserTypeName(userType.getName());
                            }
                        }
                    }
                }
                
                miniOrderServiceVoList.add(miniOrderServiceVo);

                //退款中的订单实时查询状态
                if(miniOrderService.getStatus().intValue() == MiniOrderServiceStatus.REFUNDING.getCode()){
                    queryRefundStatus(miniOrderService);
                }
            }
        }

        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(miniOrderServiceVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 查询小程序团购售后详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @return MiniOrderServiceVo
     */
    public MiniOrderServiceVo findMiniOrderServiceById(MiniOrderServiceIdDto miniOrderServiceIdDto){

        //返回的对象
        MiniOrderServiceVo miniOrderServiceVo = new MiniOrderServiceVo();

        if(miniOrderServiceIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id");
        }

        MiniOrderService miniOrderService = miniOrderServiceMapper.selectById(miniOrderServiceIdDto.getId(), miniOrderServiceIdDto.getMerId());
        if(miniOrderService == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该订单不存在");
        }

        BeanUtils.copyProperties(miniOrderService, miniOrderServiceVo);

        if(miniOrderService.getStatus() != null){
            MiniOrderServiceStatus miniOrderServiceStatus = MiniOrderServiceStatus.getByCode(miniOrderService.getStatus());
            if(miniOrderServiceStatus != null){
                miniOrderServiceVo.setStatusName(miniOrderServiceStatus.getDesc());
            }
        }

        //订单详情
        if(miniOrderService.getOrderId() != null){
            MiniOrder miniOrder = miniOrderMapper.selectById(miniOrderService.getOrderId(), miniOrderService.getMerId());
            if(miniOrder != null){
                MiniOrderVo miniOrderVo = new MiniOrderVo();
                BeanUtils.copyProperties(miniOrder, miniOrderVo);
                miniOrderServiceVo.setMiniOrderVo(miniOrderVo);
            }
        }

        //会员类型
        if(miniOrderService.getUserId() != null){
            MiniUser miniUser = miniUserMapper.selectById(miniOrderService.getUserId(), miniOrderService.getMerId());
            if(miniUser != null){
                miniOrderServiceVo.setNickName(miniUser.getNickName());
                miniOrderServiceVo.setUserRemark(miniUser.getRemark());
                if(miniUser.getUserType() != null){
                    UserType userType = userTypeMapper.selectById(miniUser.getUserType(), miniUser.getMerId());
                    if(userType != null){
                        miniOrderServiceVo.setUserType(miniUser.getUserType());
                        miniOrderServiceVo.setUserTypeName(userType.getName());
                    }
                }
            }
        }

        return miniOrderServiceVo;
    }

    /**
     * 删除小程序团购售后信息
     * @author liuqi
     * @date 2021/8/13 11:38
     * @return null
     */
    public void deleteMiniOrderService(MiniOrderServiceIdDto miniOrderServiceIdDto){
        if(miniOrderServiceIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id");
        }

        MiniOrderService miniOrderService = miniOrderServiceMapper.selectById(miniOrderServiceIdDto.getId(), miniOrderServiceIdDto.getMerId());

        if(miniOrderService == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该订单不存在");
        }

        miniOrderServiceMapper.deleteById(miniOrderServiceIdDto.getId(), miniOrderServiceIdDto.getMerId());

    }

    /**
     * 小程序团购售后取消
     * @author liuqi
     * @date 2021/8/13 11:38
     * @return null
     */
    public void cancelMiniOrderService(MiniOrderServiceIdDto miniOrderServiceIdDto){
        if(miniOrderServiceIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id");
        }

        MiniOrderService miniOrderService = miniOrderServiceMapper.selectById(miniOrderServiceIdDto.getId(), miniOrderServiceIdDto.getMerId());

        if(miniOrderService == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该售后不存在");
        }

        //取消
        int now = DateUtil.getNowTime();
        miniOrderService.setStatus(MiniOrderServiceStatus.CANCEL.getCode());
        miniOrderService.setUpdateTime(now);

        miniOrderServiceMapper.updateStatus(miniOrderService);
    }

    /**
     * 小程序团购售后拒绝退款
     * @author liuqi
     * @date 2021/8/13 11:38
     * @return null
     */
    @Transactional
    public void rejectRefundMiniOrderService(MiniOrderServiceRejectRefundDto miniOrderServiceRejectRefundDto){
        if(miniOrderServiceRejectRefundDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id");
        }

        MiniOrderService miniOrderService = miniOrderServiceMapper.selectById(miniOrderServiceRejectRefundDto.getId(), miniOrderServiceRejectRefundDto.getMerId());

        if(miniOrderService == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该售后不存在");
        }

        //如果小程序售后方式是退款模式，则还需要将订单改成不是维权订单
        if(Tools.getInteger(miniOrderService.getType()).intValue() != MiniOrderServiceType.REFUND.getCode().intValue()){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "拒绝退款只支持仅退款售后模式");
        }

        //取消
        int now = DateUtil.getNowTime();
        miniOrderService.setStatus(MiniOrderServiceStatus.REFUND_REJECT.getCode());
        miniOrderService.setRejectReason(miniOrderServiceRejectRefundDto.getRejectReason());
        miniOrderService.setUpdateTime(now);
        miniOrderServiceMapper.updateStatus(miniOrderService);

        //如果小程序售后方式是退款模式，则还需要将订单改成不是维权订单
        if(Tools.getInteger(miniOrderService.getType()).intValue() == MiniOrderServiceType.REFUND.getCode().intValue()){
            //查询订单
            MiniOrder miniOrder = miniOrderMapper.selectById(miniOrderService.getOrderId(), miniOrderService.getMerId());
            if(miniOrder != null){
                miniOrder.setRefundStatus(0); //不是维权订单
                miniOrder.setUpdateTime(now);
                miniOrder.setServiceId(null);
                miniOrderMapper.updateRefundStatus(miniOrder);
            }
        }
    }

    /**
     * 小程序团购售后同意退款
     * @author liuqi
     * @date 2021/8/13 11:38
     * @return null
     */
    @Transactional
    public void agreeRefundMiniOrderService(MiniOrderServiceIdDto miniOrderServiceIdDto){
        if(miniOrderServiceIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id");
        }

        MiniOrderService miniOrderService = miniOrderServiceMapper.selectById(miniOrderServiceIdDto.getId(), miniOrderServiceIdDto.getMerId());

        if(miniOrderService == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该售后不存在");
        }

        //查询团购订单表
        MiniOrder miniOrder = miniOrderMapper.selectById(miniOrderService.getOrderId(), miniOrderService.getMerId());
        if(miniOrder == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该订单不存在");
        }

        //判断订单是否已经付款
        if(Tools.getInteger(miniOrder.getStatus()).intValue() == MiniOrderStatus.NO_PAY.getCode()){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该订单还未付款，不能申请退款");
        }

        DeviceMiniInfo deviceMiniInfo = deviceMiniInfoMapper.selectById(miniOrder.getDeviceUniqueId(), miniOrder.getMerId());
        if(deviceMiniInfo == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该小程序不存在");
        }

        //查询会员
        MiniUser miniUser = miniUserMapper.selectById(miniOrderService.getUserId(), miniOrderService.getMerId());
        if(miniUser == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该会员不存在");
        }

        MiniTrade miniTrade_order = miniTradeMapper.selectById(miniOrder.getTradeId());
        if(miniTrade_order == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该订单交易记录不存在");
        }

        //取消
        int now = DateUtil.getNowTime();

        MiniTrade miniTrade_refund = new MiniTrade();
        miniTrade_refund.setId(IdWorker.getId());
        miniTrade_refund.setMerId(miniTrade_order.getMerId());
        miniTrade_refund.setOrderNo(miniTrade_order.getOrderNo());
        miniTrade_refund.setUserId(miniTrade_order.getUserId());
        miniTrade_refund.setBizUserId(miniTrade_order.getBizUserId());
        miniTrade_refund.setServiceId(miniOrderService.getId());
        miniTrade_refund.setOutsideCode(LocalDateTimeUtil.format(LocalDateTime.now(), "yyyyMMddHHmmss") + "_" + RandomUtil.randomStringUpper(16));
        miniTrade_refund.setSourceOutsideCode(miniTrade_order.getOutsideCode());
        miniTrade_refund.setType(2); //退款
        miniTrade_refund.setStatus(1);
        miniTrade_refund.setAmount(miniOrderService.getRefundAmount());
        miniTrade_refund.setMchId(miniTrade_order.getMchId());
        miniTrade_refund.setCreateTime(now);
        miniTrade_refund.setUpdateTime(now);
        miniTradeMapper.insertSelective(miniTrade_refund);

        //退款申请中
        CashierWechatPayParam param = new CashierWechatPayParam();
        param.setCashierAppId(deviceMiniInfo.getZfAppId());
        param.setCashierAppSecret(deviceMiniInfo.getZfAppKey());
        param.setMiniAppId(deviceMiniInfo.getMiniAppId());
        param.setDesc("订单退款");
        param.setTradeNo(miniTrade_refund.getSourceOutsideCode());
        param.setRefundTradeNo(miniTrade_refund.getOutsideCode());
        param.setExpire(String.valueOf(1800));
        param.setAttach(null);
        param.setNotifyUrl("");
        param.setTotalAmount(new BigDecimal(miniTrade_order.getAmount()).multiply(new BigDecimal(100)).intValue()); //分
        param.setTotalRefundAmount(new BigDecimal(miniOrderService.getRefundAmount()).multiply(new BigDecimal(100)).intValue());
        param.setOpenId(miniUser.getBizUserId());

        UzaiRespVo<Boolean> booleanUzaiRespVo = cashierWxPayClient.refundOrder(param);
        logger.info("--调用小程序退款接口,para={}, result={}", JSONObject.toJSONString(param), JSONObject.toJSONString(booleanUzaiRespVo));

        if(booleanUzaiRespVo != null && booleanUzaiRespVo.getData() !=null && booleanUzaiRespVo.getData()){
            miniOrderService.setStatus(MiniOrderServiceStatus.REFUNDING.getCode());
            miniOrderService.setRefundTradeNo(miniTrade_refund.getOutsideCode());
            miniOrderService.setRefundAmount(miniTrade_refund.getAmount());
            miniOrderService.setUpdateTime(now);
            miniOrderServiceMapper.updateByIdSelective(miniOrderService);
        }else{
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "调用微信小程序退款接口失败");
        }
    }

    /**
     * 小程序团购售后拒绝退货退款
     * @author liuqi
     * @date 2021/8/13 11:38
     * @return null
     */
    @Transactional
    public void rejectRefundAndGoodsMiniOrderService(MiniOrderServiceRejectRefundAndGoodsDto miniOrderServiceRejectRefundAndGoodsDto){
        if(miniOrderServiceRejectRefundAndGoodsDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id");
        }

        MiniOrderService miniOrderService = miniOrderServiceMapper.selectById(miniOrderServiceRejectRefundAndGoodsDto.getId(), miniOrderServiceRejectRefundAndGoodsDto.getMerId());

        if(miniOrderService == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该售后不存在");
        }

        if(Tools.getInteger(miniOrderService.getType()).intValue() != MiniOrderServiceType.REFUND_GOODS.getCode().intValue()){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该售后不是退货退款方式");
        }

        //取消
        int now = DateUtil.getNowTime();
        miniOrderService.setStatus(MiniOrderServiceStatus.REJECT_REFUND_AND_GOODS.getCode());
        miniOrderService.setRejectReason(miniOrderServiceRejectRefundAndGoodsDto.getRejectReason());
        miniOrderService.setMerchantExpressNo(miniOrderServiceRejectRefundAndGoodsDto.getMerchantExpressNo());
        miniOrderService.setMerchantExpressCompany(miniOrderServiceRejectRefundAndGoodsDto.getMerchantExpressCompany());
        miniOrderService.setUpdateTime(now);
        miniOrderServiceMapper.updateStatus(miniOrderService);


        //如果小程序售后方式是退款模式，则还需要将订单改成不是维权订单
        if(Tools.getInteger(miniOrderService.getType()).intValue() == MiniOrderServiceType.REFUND_GOODS.getCode().intValue()){
            //查询订单
            MiniOrder miniOrder = miniOrderMapper.selectById(miniOrderService.getOrderId(), miniOrderService.getMerId());
            if(miniOrder != null){
                miniOrder.setRefundStatus(0); //不是维权订单
                miniOrder.setUpdateTime(now);
                miniOrder.setServiceId(null);
                miniOrderMapper.updateRefundStatus(miniOrder);
            }
        }
    }

    /**
     * 小程序团购售后同意退货退款
     * @author liuqi
     * @date 2021/8/13 11:38
     * @return null
     */
    public void agreeRefundAndGoodsMiniOrderService(MiniOrderServiceIdDto miniOrderServiceIdDto){
        if(miniOrderServiceIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id");
        }

        MiniOrderService miniOrderService = miniOrderServiceMapper.selectById(miniOrderServiceIdDto.getId(), miniOrderServiceIdDto.getMerId());

        if(miniOrderService == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该售后不存在");
        }

        if(Tools.getInteger(miniOrderService.getType()).intValue() != MiniOrderServiceType.REFUND_GOODS.getCode().intValue()){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该售后不是退款方式");
        }

        //取消
        int now = DateUtil.getNowTime();
        miniOrderService.setStatus(MiniOrderServiceStatus.WAIT_BUY_SEND.getCode());
        miniOrderService.setUpdateTime(now);

        miniOrderServiceMapper.updateStatus(miniOrderService);
    }

    /**
     * 小程序团购售后拒绝退货
     * @author liuqi
     * @date 2021/8/13 11:38
     * @return null
     */
    @Transactional
    public void rejectReplaceMiniOrderService(MiniOrderServiceRejectReplaceDto miniOrderServiceRejectGoodsDto){
        if(miniOrderServiceRejectGoodsDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id");
        }

        MiniOrderService miniOrderService = miniOrderServiceMapper.selectById(miniOrderServiceRejectGoodsDto.getId(), miniOrderServiceRejectGoodsDto.getMerId());

        if(miniOrderService == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该售后不存在");
        }

        int now = DateUtil.getNowTime();

        //如果是退货退款售后方式
        if(Tools.getInteger(miniOrderService.getType()).intValue() == MiniOrderServiceType.REFUND_GOODS.getCode().intValue()){
            miniOrderService.setStatus(MiniOrderServiceStatus.REJECT_REFUND_AND_GOODS_RECEIVE.getCode());
            miniOrderService.setRejectReason(miniOrderServiceRejectGoodsDto.getRejectReason());
            miniOrderService.setMerchantExpressNo(miniOrderServiceRejectGoodsDto.getMerchantExpressNo());
            miniOrderService.setMerchantExpressCompany(miniOrderServiceRejectGoodsDto.getMerchantExpressCompany());
            miniOrderService.setMerchantReceiver(miniOrderServiceRejectGoodsDto.getMerchantReceiver());
            miniOrderService.setMerchantReceiverMobile(miniOrderServiceRejectGoodsDto.getMerchantReceiverMobile());
            miniOrderService.setMerchantReceiverAddress(miniOrderServiceRejectGoodsDto.getMerchantReceiverAddress());
            miniOrderService.setUpdateTime(now);
            miniOrderServiceMapper.updateStatus(miniOrderService);
        }else if(Tools.getInteger(miniOrderService.getType()).intValue() == MiniOrderServiceType.REPLACE.getCode().intValue()){ //仅换货售后模式，还需要判断是第一次拒绝申请还是收到货之后拒绝
            //待处理状态，表示第一次拒绝申请，此时需要将此订单改成非维权订单
            if(miniOrderService.getStatus().intValue() == MiniOrderServiceStatus.WAIT_HANDLE.getCode().intValue()){
                miniOrderService.setStatus(MiniOrderServiceStatus.REJECT_REPLACE_GOODS.getCode());
                miniOrderService.setRejectReason(miniOrderServiceRejectGoodsDto.getRejectReason());
                miniOrderService.setUpdateTime(now);
                miniOrderServiceMapper.updateStatus(miniOrderService);
                //查询订单
                MiniOrder miniOrder = miniOrderMapper.selectById(miniOrderService.getOrderId(), miniOrderService.getMerId());
                if(miniOrder != null){
                    miniOrder.setRefundStatus(0); //不是维权订单
                    miniOrder.setUpdateTime(now);
                    miniOrder.setServiceId(null);
                    miniOrderMapper.updateRefundStatus(miniOrder);
                }
            }else if(miniOrderService.getStatus().intValue() == MiniOrderServiceStatus.BUY_SEND.getCode().intValue()){ //判断状态是买家已发货
                miniOrderService.setStatus(MiniOrderServiceStatus.REJECT_REPLACE_GOODS_RECEIVE.getCode());
                miniOrderService.setRejectReason(miniOrderServiceRejectGoodsDto.getRejectReason());
                miniOrderService.setUpdateTime(now);
                miniOrderService.setMerchantExpressNo(miniOrderServiceRejectGoodsDto.getMerchantExpressNo());
                miniOrderService.setMerchantExpressCompany(miniOrderServiceRejectGoodsDto.getMerchantExpressCompany());
                miniOrderService.setMerchantReceiver(miniOrderServiceRejectGoodsDto.getMerchantReceiver());
                miniOrderService.setMerchantReceiverMobile(miniOrderServiceRejectGoodsDto.getMerchantReceiverMobile());
                miniOrderService.setMerchantReceiverAddress(miniOrderServiceRejectGoodsDto.getMerchantReceiverAddress());
                miniOrderServiceMapper.updateStatus(miniOrderService);
            }
        }
    }

    /**
     * 小程序团购售后同意退货
     * @author liuqi
     * @date 2021/8/13 11:38
     * @return null
     */
    public void agreeReplaceMiniOrderService(MiniOrderServiceIdDto miniOrderServiceIdDto){
        if(miniOrderServiceIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id");
        }

        MiniOrderService miniOrderService = miniOrderServiceMapper.selectById(miniOrderServiceIdDto.getId(), miniOrderServiceIdDto.getMerId());

        if(miniOrderService == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该售后不存在");
        }

        if(Tools.getInteger(miniOrderService.getType()).intValue() != MiniOrderServiceType.REPLACE.getCode().intValue()){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该售后不是退款方式");
        }

        //取消
        int now = DateUtil.getNowTime();
        miniOrderService.setStatus(MiniOrderServiceStatus.WAIT_BUY_SEND.getCode());
        miniOrderService.setUpdateTime(now);

        miniOrderServiceMapper.updateStatus(miniOrderService);
    }

    /**
     * 小程序团购售后同意换货发新货
     * @author liuqi
     * @date 2021/8/13 11:38
     * @return null
     */
    public void sendNewGoodsMiniOrderService(MiniOrderServiceSendNewGoodsDto miniOrderServiceSendNewGoodsDto){
        if(miniOrderServiceSendNewGoodsDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入id");
        }

        MiniOrderService miniOrderService = miniOrderServiceMapper.selectById(miniOrderServiceSendNewGoodsDto.getId(), miniOrderServiceSendNewGoodsDto.getMerId());

        if(miniOrderService == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该售后不存在");
        }

        if(Tools.getInteger(miniOrderService.getType()).intValue() != MiniOrderServiceType.REPLACE.getCode().intValue()){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该售后不是换货方式");
        }

        int now = DateUtil.getNowTime();
        miniOrderService.setStatus(MiniOrderServiceStatus.REPLACE_SUCCESS.getCode());
        miniOrderService.setMerchantExpressNo(miniOrderServiceSendNewGoodsDto.getMerchantExpressNo());
        miniOrderService.setMerchantExpressCompany(miniOrderServiceSendNewGoodsDto.getMerchantExpressCompany());
        miniOrderService.setMerchantReceiver(miniOrderServiceSendNewGoodsDto.getMerchantReceiver());
        miniOrderService.setMerchantReceiverMobile(miniOrderServiceSendNewGoodsDto.getMerchantReceiverMobile());
        miniOrderService.setMerchantReceiverAddress(miniOrderServiceSendNewGoodsDto.getMerchantReceiverAddress());
        miniOrderService.setUpdateTime(now);

        miniOrderServiceMapper.updateStatus(miniOrderService);
    }

    /**
     * 查询亏款状态
     * @author liuqi
     * @date 2021/8/13 11:38
     * @return null
     */
    public void queryRefundStatus(MiniOrderService miniOrderService){

        int now = DateUtil.getNowTime();

        //查询交易记录
        MiniTrade miniTrade = miniTradeMapper.selectByOutsideCode(miniOrderService.getRefundTradeNo());
        if(miniTrade != null){
            //交易中
            if(miniTrade.getStatus() == 1){
                CashierWechatPayQueryParam param = new CashierWechatPayQueryParam();
                param.setTradeNo(miniTrade.getSourceOutsideCode());
                param.setRefundTradeNo(miniTrade.getOutsideCode());
                UzaiRespVo<WxOrderQueryDto> uzaiRespVo = cashierWxPayClient.queryRefundOrder(param);
                logger.info("--调用小程序查询退款状态接口,para={}, result={}", JSONObject.toJSONString(param), JSONObject.toJSONString(uzaiRespVo));
                if(uzaiRespVo != null && uzaiRespVo.getCode() == 200) {
                    WxOrderQueryDto orderQueryDto = uzaiRespVo.getData();
                    if (orderQueryDto != null) {
                        //支付成功
                        if (TradeStatusEnum.SUCCESS.equals(orderQueryDto.getStatus())) {
                            miniTrade.setStatus(MiniTradeStatus.TRADE_SUCCESS.getCode());
                            miniTrade.setOutsideStatus(1);
                            miniTrade.setFinishTime(now);
                            miniTrade.setUpdateTime(now);
                            miniTradeMapper.updateStatus(miniTrade);

                            miniOrderService.setStatus(MiniOrderServiceStatus.REFUND_SUCCESS.getCode());
                            miniOrderService.setUpdateTime(now);
                            miniOrderServiceMapper.updateStatus(miniOrderService);

                            //查询此订单
                            MiniOrder miniOrder = miniOrderMapper.selectById(miniOrderService.getOrderId(), miniOrderService.getMerId());
                            if(miniOrder != null){
                                miniOrder.setStatus(MiniOrderStatus.REFUND.getCode());
                                miniOrder.setUpdateTime(now);
                                miniOrderMapper.updateStatus(miniOrder);
                            }

                        } else if (TradeStatusEnum.ABNORMAL.equals(orderQueryDto.getStatus())) {
                            miniTrade.setStatus(MiniTradeStatus.TRADE_FAIL.getCode());
                            miniTrade.setOutsideStatus(0);
                            miniTrade.setFinishTime(now);
                            miniTrade.setUpdateTime(now);
                            miniTradeMapper.updateStatus(miniTrade);

                            miniOrderService.setStatus(MiniOrderServiceStatus.REFUND_FAIL.getCode());
                            miniOrderService.setUpdateTime(now);
                            miniOrderServiceMapper.updateStatus(miniOrderService);

                        } else if (TradeStatusEnum.CLOSED.equals(orderQueryDto.getStatus())) {
                            miniTrade.setStatus(MiniTradeStatus.TRADE_CANCEL.getCode());
                            miniTrade.setOutsideStatus(0);
                            miniTrade.setFinishTime(now);
                            miniTrade.setUpdateTime(now);
                            miniTradeMapper.updateStatus(miniTrade);

                            miniOrderService.setStatus(MiniOrderServiceStatus.REFUND_FAIL.getCode());
                            miniOrderService.setUpdateTime(now);
                            miniOrderServiceMapper.updateStatus(miniOrderService);
                        }
                    }
                }
            }
        }
    }

}
